<?php
class InstallDatabaseController{
	private $_tabels;
	private $_urls;
	
	function __construct($__parameters=null){
		$this->_parameters = $__parameters;
	}
	
	public function indexAction($dbx=null){	
		global $dbl,$parameters;	
		$db = (!is_null($dbx) && is_object($dbx)) ? $dbx : $dbl;
		// usuwanie tabel	
		switch($parameters['drivers']['driver']){	
			case 'sqlite': 
				tools::__adodb('exec',"PRAGMA encoding = \"UTF-8\";");
				$__table_list = tools::__adodb('getAssoc',"SELECT name FROM sqlite_master WHERE type='table'",true,$db,$parameters['drivers']['driver']);
				break;
			case 'mysql': 
				$__table_list = tools::__adodb('getAssoc',"show tables",true,null,$parameters['drivers']['driver']);
				break;
		}	
		if	(is_array($__table_list)){
		foreach ($__table_list as $__table){
			tools::__adodb('exec',"DROP TABLE {$__table['name']}",true,$db,$parameters['drivers']['driver']);
		}}

		// zakładanie tabel
	
		$this->installDatabaseTabels($parameters['drivers']['dbinstall'],$parameters['drivers']['driver'],$db);
		$this->install_urls($db);
		
		$this->install_admin_user($db);
	}

	/**
	 * instalacja tabel CMSa
	 * 
	 * @param $xmlFilePath
	 * @return unknown_type
	 */
	private function installDatabaseTabels($xmlFilePath="../ini/install_tables.xml",$driver,$db=null){
		global $parameters;
		if (file_exists($xmlFilePath)){
			$xml = simplexml_load_file($xmlFilePath);
		}else{
			die("brak pliku XML {$xmlFilePath}");
		}
		switch($driver){
			case "sqlite":		
				foreach ($xml as $table) {
					$i__ = 0;
					$all__ = 0;
					foreach ( $table->column as $column){ $all__++; }
					$q_create_table__ = "CREATE TABLE {$table[0]["name"]} ( ";
					$q_column__ = "";
					$unique__ = ( !empty($table->unique[0]) ) ? ", UNIQUE ( {$table->unique[0]} )" : "";
					foreach ( $table->column as $column){
						$i__++;
						$q_column__ .= " {$column[0]['cName']} {$column[0]['cType']} ".(($column[0]['cWidth'] != "" && $column[0]['cType']!= "text" && $column[0]['cType']!= "datetime") ? " ({$column[0]['cWidth']}) " : "");
						$q_column__ .=  (( $column[0]['cPrimaryKey'] == 1 ) ? " PRIMARY KEY " : "") ;
						$q_column__ .=  (( !empty($column[0]['cDefault']) ) ? " default '{$column[0]['cDefault']}' " : "") ;
						$q_column__ .=  " {$column[0]['cNull']} " ;
						$q_column__ .= ($all__ != $i__ ) ? "," : " {$unique__} )";	
					}
					$q_create_table__ .= $q_column__;
					tools::__adodb("exec",$q_create_table__,true,$db,$parameters['drivers']['driver']);
				}
				break;
			case "mysql":
				foreach ($xml as $table) {
					$i__ = 0;
					$all__ = 0;
					foreach ( $table->column as $column){ $all__++; }
					$q_create_table__ = "CREATE TABLE {$table[0]["name"]} ( ";
					$q_column__ = "";
					$unique__ = ( !empty($table->unique[0]) ) ? ", UNIQUE ( {$table->unique[0]} )" : "";
					$primary__ = ( !empty($table->primary[0]) ) ? ", PRIMARY KEY ( {$table->primary[0]} )" : "";
					$engine__ = ( !empty($table->engine[0]) ) ? " ENGINE =  {$table->engine[0]} " : " ENGINE =  MYISAM ";
					foreach ( $table->column as $column){
						$i__++;
						$q_column__ .= " {$column[0]['cName']} {$column[0]['cType']} " ;
						$q_column__ .=  (( !empty($column[0]['cWidth']) ) ? " ( {$column[0]['cWidth']} ) " : "") ;
						$q_column__ .=  (( $column[0]['cAutoIncrement'] == 1 && $column[0]['cPrimaryKey'] == 1) ? " AUTO_INCREMENT PRIMARY KEY " : "") ;
						$q_column__ .=  (( !empty($column[0]['cDefault']) ) ? " default '{$column[0]['cDefault']}' " : "") ;
						$q_column__ .=  " {$column[0]['cNull']} " ;
						$q_column__ .= ($all__ != $i__ ) ? "," : " {$primary__} {$unique__}) {$engine__} ";	
					}
					$q_create_table__ .= $q_column__;
					tools::__adodb("exec",$q_create_table__,false,$db);
				}
				break;				
		}
	}
	
	/**
	 * domyślne dane i linki
	 * @return unknown_type
	 */
	public function install_urls($db=null){
		global $parameters;
		if (file_exists($parameters['drivers']['urlspanel'])){
			$xml = simplexml_load_file($parameters['drivers']['urlspanel']);
		}else{
			die("brak pliku XML");
		}		
		foreach ($xml as $page) {
//			print $page[0];
			$__i = 0;
			$__max = 0;
			foreach ( $page->attributes() as $__key) $__max++;
			
			$__q_add_pages = "INSERT INTO ".PAGES." ( ";
			$__q_files = "";
			$__q_value = "VALUES (";
			
			foreach ( $page->attributes() as $__key => $__value ) {
//			    print "<div class='coords'>$__key: $__value</div>\n";
			   if ( $__key == "id_page")  $__id_page = $__value;
	    		$__i++;
				$__q_files .= "{$__key}";
				$__q_files .= ($__max != $__i ) ? "," : ")";	
				$__q_value .= (empty($__value)) ? "NULL" : "'{$__value}'";
				$__q_value .= ($__max != $__i ) ? "," : ");";			    
			}
			$__q_add_pages .= $__q_files.$__q_value;
			tools::__adodb('exec',$__q_add_pages,true,$db);
//			echo $__q_add_pages."<br/>";
			
			foreach ( $page->page_lang as $language){
//				print $language[0];
				$__i = 0;
				$__max = 0;
				foreach ( $language->attributes() as $__key) $__max++;
				
				$__q_add_pages_lang = "INSERT INTO ".PLANG." ( id_page, page_name, ";
				$__q_files = "";
				$__q_value = "VALUES ( {$__id_page},".tools::__mres($language[0]).", ";	
				foreach ( $language->attributes() as $__key => $__value ) {
//			   		print "<div class='coords'>$__key: $__value</div>\n";
		    		$__i++;
					$__q_files .= "{$__key}";
					$__q_files .= ($__max != $__i ) ? "," : ")";	
					$__q_value .= (empty($__value)) ? "NULL" : "'{$__value}'";
					$__q_value .= ($__max != $__i ) ? "," : ");";			    
				}
				$__q_add_pages_lang .= $__q_files.$__q_value;
//				echo $__q_add_pages_lang."<br/>";
				tools::__adodb('exec',$__q_add_pages_lang,true,$db);
			}
						
			foreach ( $page->section as $section){
//				print $section[0];
				$__i = 0;
				$__max = 0;
				foreach ( $section->attributes() as $__key) $__max++;
				
				$__q_add_pages_section = "INSERT INTO ".THEME." ( id_page, section_body, ";
				$__q_files = "";
				$__q_value = "VALUES ( {$__id_page},".tools::__mres($section[0]).", ";	
				foreach ( $section->attributes() as $__key => $__value ) {
//			   		print "<div class='coords'>$__key: $__value</div>\n";
		    		$__i++;
					$__q_files .= "{$__key}";
					$__q_files .= ($__max != $__i ) ? "," : ")";	
					$__q_value .= (empty($__value)) ? "NULL" : "'{$__value}'";
					$__q_value .= ($__max != $__i ) ? "," : ");";			    
				}
				$__q_add_pages_section .= $__q_files.$__q_value;
//				echo $__q_add_pages_section."<br/>";				
				tools::__adodb('exec',$__q_add_pages_section,true,$db);
			}
			
			
		}
		
	}
	
	public function install_admin_user($dbx=null){
		global $parameters;
		require_once 'Panel/RegisterModel.php';
		$user__ = array(
			'nazwa_uzytkownika'=>$parameters['admin']['user'],
			'haslo'=> $parameters['admin']['pass'],
			'imie'=>$parameters['admin']['name'],
			'nazwisko'=>$parameters['admin']['surn'],
			'email'=>$parameters['admin']['mail'],
			'telefon'=>'',
			'adres'=>'',
			'kodpocztowy'=>'',
			'miasto'=>'',
			'firma'=>'',
			'nip'=>'',
			'stanowisko'=>'a'
		);
		$__result = RegisterModel::add_user($user__,$dbx,false);	
	}
}
?>